package edu.sfsu.powerrangers.jeopardy.editor;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.List;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ValuesPanel extends JPanel {
	private static final long serialVersionUID = 1L;
	
	private JPanel valuesPanel;
	
	public ValuesPanel(int count) {
		super(new BorderLayout(4,4));
		valuesPanel = new JPanel(new GridLayout(0,1,4,4));
		while (count-->0) {
			valuesPanel.add(new ValuePanel());
		}
		add(Box.createRigidArea(new JTextField("M").getPreferredSize()), BorderLayout.PAGE_START);
		add(valuesPanel, BorderLayout.CENTER);
	}
	
	public int getValueCount() {
		return valuesPanel.getComponentCount();
	}
	
	public ValuePanel getValue(int i) {
		return (ValuePanel)valuesPanel.getComponent(i);
	}
	
	public void addValue(ValuePanel value) {
		valuesPanel.add(value);
		valuesPanel.validate();
	}
	
	public void addValue(int index, ValuePanel value) {
		valuesPanel.add(value, index);
		valuesPanel.validate();
	}
	
	public void addValue(ValuePanel value, int index) {
		valuesPanel.add(value, index);
		valuesPanel.validate();
	}
	
	public void removeValue(int index) {
		valuesPanel.remove(index);
		valuesPanel.validate();
	}
	
	public void removeValue(ValuePanel value) {
		valuesPanel.remove(value);
		valuesPanel.validate();
	}
	
	public void moveValueUp(int index) {
		ValuePanel value = (ValuePanel)valuesPanel.getComponent(index);
		valuesPanel.remove(index);
		index--;
		if (index < 0) {
			index = 0;
		}
		valuesPanel.add(value, index);
		valuesPanel.validate();
	}
	
	public void moveValueDown(int index) {
		ValuePanel value = (ValuePanel)valuesPanel.getComponent(index);
		valuesPanel.remove(index);
		index++;
		if (index > valuesPanel.getComponentCount()) {
			index = valuesPanel.getComponentCount();
		}
		valuesPanel.add(value, index);
		valuesPanel.validate();
	}
	
	public void setValueCount(int count) {
		while (valuesPanel.getComponentCount() > count) {
			valuesPanel.remove(count);
		}
		while (valuesPanel.getComponentCount() < count) {
			valuesPanel.add(new ValuePanel());
		}
		valuesPanel.validate();
	}
	
	public List<Integer> getValues() {
		List<Integer> values = new Vector<Integer>();
		Component[] comps = valuesPanel.getComponents();
		for (int i = 0; i < comps.length; i++) {
			values.add(((ValuePanel)comps[i]).getValue());
		}
		return values;
	}
	
	public void setValues(List<Integer> values) {
		valuesPanel.removeAll();
		for (int value : values) {
			ValuePanel vp = new ValuePanel();
			vp.setValue(value);
			valuesPanel.add(vp);
		}
		valuesPanel.validate();
	}
}
